#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/10/17 22:08
# @Author  : when
# @File    : xcy_proxy.py
# @Description : 协采云代理
import json
import requests

from components.proxy_utils.base_proxy import BaseProxy
try:
    from components.proxy_utils.config import XCY_USERNAME
    from components.proxy_utils.config import XCY_PASSWD
    from components.proxy_utils.config import XCY_KEY
except ImportError:
    # 默认测试账户
    XCY_USERNAME = "xxxx"
    XCY_PASSWD = "xxxx"
    XCY_KEY = "xxxx"

XCY_URL = f"http://{XCY_USERNAME}.user.xiecaiyun.com/api/proxies"
XCY_COUNT = 1
XCY_DEFAULT = "rand=true&action=getJSON&word=&norepeat=false&detail=false&ltime=0"


class XcyProxy(BaseProxy):
    """
    协采云代理: http://xiecaiyun.com/
    接入指南: https://www.yuque.com/lidaxiong/shewkm
    """
    def __init__(self):
        self.url = f"{XCY_URL}?key={XCY_KEY}&count={XCY_COUNT}&{XCY_DEFAULT}"
        self.auth = f"{XCY_USERNAME}:{XCY_PASSWD}"

    def get_proxy(self):
        """
        获取代理
        :return: ip:port
        """
        res = requests.get(self.url)
        assert (res.status_code == 200), f"获取代理失败，http code: {res.status_code}"
        data = json.loads(res.text)
        if data.get("success", False):
            result = data['result'][0]
            return f"{self.auth}@{result['ip']}:{result['port']}"
        assert False, f"获取代理失败, data={data}"


if __name__ == '__main__':
    xcy_proxy = XcyProxy()
    proxy_url = xcy_proxy.get_proxy()
    print(f"proxy_url={proxy_url}")
